<?php

namespace App\Modules\Ws\Controller;

use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Logger\Logger;
use Hyperf\Utils\Str;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;

abstract class BasicController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onMessage($server, Frame $frame): void
    {
        $data = json_decode($frame->data, true);
        if (json_last_error() != JSON_ERROR_NONE || !isset($data['event'])) {
            Logger::info('skip message invalid: ' . $frame->data);
            $server->close($frame->fd);
        }

        $method = Str::camel('on_' . $data['event']);
        if (method_exists($this, $method)) {
            $this->$method($server, $frame, $data);
        } else {
            Logger::info('event method not exists: ' . $method);
        }
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        // TODO: Implement onClose() method.
        var_dump('closed');
    }

    public function onOpen($server, Request $request): void
    {
        // TODO: Implement onOpen() method.
        $server->push($request->fd, 'Opened');
    }
}